#include <QTranslator>
#include <QQmlContext>

#include "controlservice.h"
#include "beans/maskedmousearea.h"
#include "beans/systemconfig.h"
#include "beans/dealmsgpacket.h"

ControlService::ControlService(QObject *parent):QObject(parent)
{
    //注册类型
    qmlRegisterType<MaskedMouseArea>("MaskedMouseArea",1,0,"MaskedMouseArea");

    m_App = (QCoreApplication*)parent;
    __initBeans();
    __initQml(parent);
    __initRegistBean();
    __initSlots();
}

ControlService::~ControlService(){
    //*按照顺序释放
    m_qmlEngine = nullptr;
    m_MsgControl = nullptr;
    m_SmallPicThread = nullptr;
    m_BigPicThread = nullptr;
}

void ControlService::__initBeans()
{
   m_MsgControl = std::make_shared<MsgControl>();
   m_qmlEngine = std::make_shared<QQmlApplicationEngine>();
   m_SmallPicThread = std::make_shared<DealSmallPictureThread>();
   m_BigPicThread = std::make_shared<DealBigPictureThread>();
}

void ControlService::__initQml(QObject *parent){
    if(m_qmlEngine){
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        connect(m_qmlEngine.get(), &QQmlApplicationEngine::objectCreated,
                         parent, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        m_qmlEngine->load(url);
    }

    const QString lan = SystemConfig::getInstance()->value("setting/language","en").toString();
    if("en" == lan){
        setSoftLanguage("en");
    }else if("cn" == lan){
        setSoftLanguage("cn");
    }else{
        setSoftLanguage("en");
    }
}

void ControlService::__initRegistBean(){
    m_qmlEngine.get()->rootContext()->setContextProperty("printControl",m_MsgControl.get());
}

void ControlService::setSoftLanguage(const QString& type){
    QTranslator translator;
    if("cn" == type){
        translator.load(":/zh_CN.qm");
    }else if("en" == type){
        translator.load(":/en_US.qm");
    }else{
        translator.load(":/en_US.qm");
    }
    m_App->installTranslator(&translator);
    m_qmlEngine->retranslate();
}

void ControlService::doChangeLanguage(const QString& type){
    setSoftLanguage(type);
    SystemConfig::getInstance()->setValue("setting/language",type);
}

void ControlService::__initSlots(){

}
